﻿CREATE PROCEDURE [dbo].[ArhivePriceFor]
(--Архивирует данные последнего загруженного прайса для конкретного конрагента
	@ContragentId int
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @datPriceDate smalldatetime, @intNextId int
	SET NOCOUNT ON

IF (@ContragentId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @datPriceDate = PriceDate FROM PR.PriceInfo WHERE ContragentId = @ContragentId

IF @@rowcount = 0 RETURN 0

DELETE FROM DIArhive.dbo.PriceInfo WHERE ContragentId = @ContragentId AND PriceDate = @datPriceDate
-- данные из таблиц dbo.PriceLinesNOTParsed и dbo.PriceLinesParsed удаляются по FK CASCADE

INSERT INTO [DIArhive].[dbo].[PriceInfo] 
(ContragentId,Loaded,PriceDate,Note,MD,MW)
SELECT ContragentId,Loaded,PriceDate,Note,MD,MW
FROM [PR].[PriceInfo] WHERE ContragentId = @ContragentId AND PriceDate = @datPriceDate

SELECT @intNextId = SCOPE_IDENTITY()

INSERT INTO [DIArhive].[dbo].[PriceLinesParsed]
(PriceInfoId,GoodsVsContragentsId,GoodsId,Price,Qntty,
NDSTax,BatchNumber,ReadyBefore,ReestrPrice,ReestrDate,Note)
SELECT @intNextId,GoodsVsContragentsId,GoodsId,Price,Qntty,
NDSTax,BatchNumber,ReadyBefore,ReestrPrice,ReestrDate,Note
FROM [PR].[PriceLinesParsed] WHERE ContragentId = @ContragentId

INSERT INTO [DIArhive].[dbo].[PriceLinesNOTParsed]
(PriceInfoId,GoodsCode,GoodsName,CountryName,ManufacturerName,Price,Qntty,NDSTax,BatchNumber,ReadyBefore,
ReestrPrice,ReestrDate,Mandatory,Drastic,RetailPack,ManufactureBarCode,GNVLS,Note)
SELECT @intNextId,GoodsCode,GoodsName,CountryName,ManufacturerName,Price,Qntty,NDSTax,BatchNumber,ReadyBefore,
ReestrPrice,ReestrDate,Mandatory,Drastic,RetailPack,ManufactureBarCode,GNVLS,Note
FROM [PR].[PriceLinesNOTParsed] WHERE ContragentId = @ContragentId

DELETE FROM [PR].[PriceLinesParsed] WHERE ContragentId = @ContragentId
DELETE FROM [PR].[PriceLinesNOTParsed] WHERE ContragentId = @ContragentId
DELETE FROM [PR].[PriceInfo] WHERE ContragentId = @ContragentId

RETURN 0
